<template>
  <div class="container">
    <h2 class="title">公式模板配置</h2>
    <form @submit.prevent="submitForm" class="form">
      <div class="form-group">
        <label>模板名称:</label>
        <input type="text" v-model="templateName" required class="form-control" placeholder="请输入模板名称"
               @input="searchTemplateName" v-on:focus="searchTemplateName">

        <div v-if="showHistory" class="history-list">
          <ul>
            <li v-for="name in filteredTemplateNames" :key="name" @click="selectTemplate(name)">
              {{ name }}
            </li>
          </ul>
        </div>
      </div>
      <div class="form-group">
        <label>模板内容:</label>
        <input type="text" v-model="template" required class="form-control"
               placeholder="请输入模板内容,例如: 值0 = 值1 值2,值必须包含'值',这样规则会自动添加"
               @input="parseTemplateAndUpdateRules">
      </div>
      <div class="form-group">
        <label>生成数量:</label>
        <input type="number" v-model.number="num" required class="form-control" placeholder="请输入生成数量">
      </div>
      <h3>值规则配置</h3>
      <div class="rules-container">
        <div v-for="(rule, index) in rules" :key="index" class="rule">
          <div class="form-group">
            <label>值:</label>
            <input type="text" v-model="rule.name" required class="form-control" placeholder="请输入值名称">
          </div>
          <div class="form-group">
            <label>类型:</label>
            <select v-model="rule.type" required class="form-control">
              <option value="CUSTOM">自定义数据</option>
              <option value="ALPHA">随机字母</option>
              <option value="NUM">随机整数</option>
              <option value="FLOAT">随机小数</option>
            </select>
          </div>
          <div v-if="rule.type === 'CUSTOM'" class="form-group">
            <label>数据:</label>
            <input type="text" v-model="rule.data" class="form-control" placeholder="多个数据用逗号分隔">
          </div>
          <button type="button" @click="removeRule(index)" class="btn btn-danger">删除</button>
        </div>
      </div>
      <button type="button" @click="addRule" class="btn btn-primary">添加值规则</button>
      <br><br>
      <button type="submit" class="btn btn-success">提交</button>
    </form>
  </div>
</template>


<script>
import axios from 'axios';
import * as XLSX from 'xlsx';
import {saveAs} from 'file-saver';

var host = 'http://52.83.227.194:18002';


export default {
  data() {
    return {
      templateName: '',
      template: '',
      num: null,
      rules: [],
      showHistory: true,
      historyTemplateNames: [],      // 存储历史模板名称
      filteredTemplateNames: [],     // 存储筛选后的历史模板名称
    }
  },
  methods: {
    parseTemplate(template) {
      const placeholderRegex = /值\d+/g;
      const placeholders = Array.from(new Set(template.match(placeholderRegex)));

      // 映射占位符到规则对象
      return placeholders.map(placeholder => {
        // 查找当前占位符在 this.rules 中是否已存在
        const existingRule = this.rules.find(rule => rule.name === placeholder);

        return {
          name: placeholder,
          type: existingRule ? existingRule.type : 'CUSTOM',
          data: existingRule ? existingRule.data : ''
        };
      });
    },
    searchTemplateName() {
      // 调用后端接口进行模板名称搜索
      axios.get(host + '/formula/list', {
        params: {templateName: this.templateName}
      }).then(response => {
        // 更新筛选后的历史模板名称列表
        this.filteredTemplateNames = response.data.data;
      }).catch(error => {
        console.error('Search Error:', error);
      });
      this.showHistory = true;
    },
    selectTemplate(name) {
      this.templateName = name;
      this.showHistory = false;

      // 调用后端接口获取模板详情，并回显数据
      axios.get(host + '/formula/detail', {
        params: {templateName: name}
      }).then(response => {

        const data = response.data.data;
        this.templateName = data.templateName;
        this.template = data.template;
        this.rules = data.rules; // 需要根据实际返回数据结构进行调整
        this.num = data.num;
        this.templateName = data.templateName;
        // 其他需要回显的数据...
      }).catch(error => {
        console.error('Details Error:', error);
      });
    },
    addRule() {
      this.rules.push({
        name: '',
        type: 'CUSTOM',
        data: ''
      });
    },
    removeRule(index) {
      this.rules.splice(index, 1);
    },
    parseTemplateAndUpdateRules() {
      this.rules = this.parseTemplate(this.template);
    },
    submitForm() {
      const data = {
        templateName: this.templateName,
        template: this.template,
        num: this.num,
        rules: this.rules.map(rule => ({
          name: rule.name,
          data: rule.data,
          type: rule.type
        }))
      };


      const apiEndpoint = host + '/formula/generate';

      axios.post(apiEndpoint, data)
          .then(response => {
            const formulas = response.data.data;
            const worksheet = XLSX.utils.json_to_sheet(formulas.map(formula => ({formula})));
            const workbook = XLSX.utils.book_new();
            XLSX.utils.book_append_sheet(workbook, worksheet, 'Formulas');
            const excelBuffer = XLSX.write(workbook, {bookType: 'xlsx', type: 'array'});
            const excelData = new Blob([excelBuffer], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'});
            saveAs(excelData, 'formulas.xlsx');
            console.log('Success:', response.data.data);
            alert('公式已生成并下载为Excel文件!');
          })
          .catch(error => {
            console.error('Error:', error);
            alert('生成失败，请稍后再试。');
          });
    }
  }
}
</script>

<style scoped>
.container {
  max-width: 600px;
  margin: 0 auto;
  padding: 20px;
}

.title {
  text-align: center;
  margin-bottom: 20px;
}

.form-group {
  margin-bottom: 15px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  font-weight: bold;
}

.form-control {
  width: 100%;
  padding: 3px;
  border-radius: 4px;
  border: 1px solid #ccc;
}

.rules-container {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}

.rule {
  background-color: #f5f5f5;
  padding: 10px;
  border-radius: 4px;
  margin-bottom: 10px;
  width: 24%;
  box-sizing: border-box;
}

@media (max-width: 992px) {
  .rule {
    width: 32%;
  }
}

@media (max-width: 768px) {
  .rule {
    width: 49%;
  }
}

@media (max-width: 480px) {
  .rule {
    width: 100%;
  }
}

.btn {
  padding: 8px 16px;
  border-radius: 4px;
  border: none;
  color: #fff;
  cursor: pointer;
}

.btn-primary {
  background-color: #007bff;
}

.btn-success {
  background-color: #28a745;
}

.btn-danger {
  background-color: #dc3545;
}

.history-list {
  position: absolute;
  width: calc(100% - 30px); /* 假设左右padding总共为30px，使用calc()函数计算实际宽度 */
  left: 15px; /* 我们添加与.form-group一致的左边距 */;
  background-color: #fff;
  border: 1px solid #ddd;
  right: 0;
  z-index: 1000; /* 确保列表位于其他元素之上 */
  max-height: 200px; /* 限制列表的最大高度 */
  overflow-y: auto; /* 超过最大高度时，内容可滚动 */
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1); /* 添加一些阴影效果，使列表更有立体感 */
}

.history-list ul {
  list-style-type: none;
  padding: 0;
  margin: 0;
}

.history-list li {
  padding: 10px;
  cursor: pointer;
}

.history-list li:hover {
  background-color: #f0f0f0;
}
</style>